package com.aote.util.readProperties;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * 该类为读取HttpUrl.properties属性文件所用
 */
public class ReadProperties {
    private static Map<String, String> maps = new HashMap<>();
    private static Logger logger = Logger.getLogger(ReadProperties.class);

    static {
        try {
            readProperties();
        } catch (IOException e) {
            logger.error(e);
        }
    }

    public static String getProperties(String key) throws IOException {
        if (!maps.containsKey(key)) {
            logger.info("尝试获取HttpUrl.properties中的属性值失败，并未在私有集合中找到该属性，所以重载属性文件");
            new ReadProperties().readProperties();
            logger.info("HttpUrl.properties重载完成。准备再获取对应key的属性值");
            if (maps.containsKey(key)) {
                logger.info("key属性值获取成功！");
                return maps.get(key);
            } else {
                logger.info("key属性值获取失败！");
                throw new RuntimeException("HttpUrl.properties中并没有一个名为" + key + "的属性");
            }
        } else {
            return maps.get(key);
        }
    }

    private static void readProperties() throws IOException {
        Properties properties = new Properties();
        properties.load(ReadProperties.class.getClassLoader()
                .getResourceAsStream("HttpUrl.properties"));
        Set<Object> set = properties.keySet();
        set.forEach((key) -> {
            maps.put((String) key, properties.getProperty((String) key));
        });
    }
}
